<!-- 模板界面,使用时全局替换
    doctorDuty  为此页要维护的信息(例如department)
    doctorDutyData 为此页面要维护的信息的数组(例如deptData) 
    outpatientDoctorId    为此页面要维护的信息的一个成员(例如deptName之于department),作为示例使用
    -->
<template>
  <div>
    医生排班界面
    <el-button type="primary" plain @click="addButtonClicked">添加</el-button>
    <el-button type="primary" plain @click="batchRemoveButtonClicked">批量删除</el-button>
    <el-button type="primary" plain @click="queryButtonClicked">查询</el-button>
    <el-button type="primary" plain @click="queryResetButtonClicked">重置</el-button>
    <el-table :data="doctorDutyData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column>
        <!-- <el-checkbox></el-checkbox> -->
        <el-table-column type="selection" width="55"></el-table-column>
      </el-table-column>
      <!-- <el-table-column prop="date" label="日期" width="180"></el-table-column> -->
      <el-table-column prop="outpatientDoctorI" label="医生id" width="180"></el-table-column>
      <el-table-column prop="doctorName" label="医生姓名" width="180"></el-table-column>
      <el-table-column prop="noonName" label="午别" width="180"></el-table-column>
      <el-table-column prop="dayOfWeek" label="星期" width="180"></el-table-column>
      <!-- 其实在el-table下,书写的各个列的信息,然后会根据userData自动生成n行 -->

      <el-table-column align="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加和修改 -->
    <el-dialog title="添加" :visible.sync="addDialogVisible">
      <el-form :model="doctorDuty" ref="form" label-width="100px">
        <el-form-item label="日期" prop="week">
          <el-select v-model="doctorDuty.dayOfWeek" placeholder="请选择日期">
            <el-option
              v-for="item in weekdays"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="午别" prop="noon">
          <el-select v-model="doctorDuty.noon" placeholder="请选择午别">
            <el-option
              v-for="item in noons"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生" prop="doctor">
          <el-select v-model="doctorDuty.outpatientDoctorI" placeholder="请选择医生">
            <el-option
              v-for="item in doctor"
              :key="item.id"
              :label="item.doctorName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 筛选界面 -->
    <el-dialog title="筛选" :visible.sync="queryDialogVisible">
      <el-form :model="doctorDutyQuery" ref="form" label-width="100px">
        <el-form-item label="日期" prop="week">
          <el-select v-model="doctorDutyQuery.dayOfWeek" placeholder="请选择日期">
            <el-option
              v-for="item in weekdays"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="午别" prop="noon">
          <el-select v-model="doctorDutyQuery.noon" placeholder="请选择午别">
            <el-option
              v-for="item in noons"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生" prop="doctor">
          <el-select v-model="doctorDutyQuery.outpatientDoctorId" placeholder="请选择医生">
            <el-option
              v-for="item in doctor"
              :key="item.id"
              :label="item.doctorName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="queryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="queryConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <div class="block">
      <span class="demonstration">显示总数</span>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPageNum"
        :page-sizes="[1, 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecord"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  insert,
  update,
  deleteElem,
  getPage,
  getAll,
  getAllType
} from "@/api/doctorDuty.js";
import { getAll as getAllDoctor } from "@/api/doctor.js";
export default {
  mounted() {
    // 渲染完成
    this.loadPageData();
    this.loadDoctor();
  },
  data() {
    return {
      // 复选框
      multipleSelection: [],
      // 分页
      pageSize: 1,
      totalRecord: 3,
      currentPageNum: 1,
      // 对话框
      addDialogVisible: false,
      queryDialogVisible: false,
      // 局部对象
      weekdays: [
        { label: "周一", value: 1 },
        { label: "周二", value: 2 },
        { label: "周三", value: 3 },
        { label: "周四", value: 4 },
        { label: "周五", value: 5 },
        { label: "周六", value: 6 },
        { label: "周日", value: 7 }
      ],
      noons: [
        { label: "白天", value: true },
        { label: "夜间", value: false }
      ],
      doctor: [],
      doctorDict: {},

      /* 补全信息 */
      /* {noon,dayOfWeek,outpatientDoctorId} */
      doctorDuty: {
        id: "",
        noon: "",
        dayOfWeek: "",
        outpatientDoctorI: "",
        doctorName: "",
        noonName: ""
      },
      /* 补全信息 */
      doctorDutyQuery: {
        id: "",
        noon: "",
        dayOfWeek: "",
        outpatientDoctorId: "",
        doctorName: "",
        noonName: ""
      },
      // 对象数组
      doctorDutyData: []
    };
  },
  methods: {
    addButtonClicked() {
      // 清空
      /* 补全信息 */
      this.doctorDuty.id = "";
      this.doctorDuty.outpatientDoctorI = "";
      this.doctorDuty.noon = "";
      this.doctorDuty.noonName = "";
      this.doctorDuty.dayOfWeek = "";
      this.doctorDuty.doctorName = "";
      this.updateFlag = false;
      this.addDialogVisible = true;
      this.loadPageData();
    },
    loadPageData() {
      // 这个函数会更新总个数和数组中的信息
      // 查询条件
      /* 转换格式 */
      if (this.doctorDutyQuery.outpatientDoctorId !== "") {
        this.doctorDutyQuery.outpatientDoctorId = parseInt(
          this.doctorDutyQuery.outpatientDoctorId
        );
      }
      let pageParam = {
        /* 补全信息 */
        noon: this.doctorDutyQuery.noon,
        dayOfWeek: this.doctorDutyQuery.dayOfWeek,
        outpatientDoctorId: this.doctorDutyQuery.outpatientDoctorId,
        currentPage: this.currentPageNum,
        pageSize: this.pageSize
      };
      console.log("send getPage: ", pageParam);
      getPage(pageParam).then(response => {
        if (response.data.code == 0) {
          this.currentPageNum = parseInt(response.data.data.current);
          this.doctorDutyData = response.data.data.records;
          this.doctorDutyData.forEach(item => {
            item.doctorName = this.doctorDict[item.outpatientDoctorI];
            if (item.noon) {
              item.noonName = "白天";
            } else {
              item.noonName = "夜间";
            }
          });

          this.totalRecord = parseInt(response.data.data.total);
          console.log("getPage: ", this.doctorDutyData);
        } else {
          console.log("getPage ERROR!!");
        }
      });
    },
    loadDoctor() {
      this.doctor = [];
      console.log("send getAllDoctor");
      getAllDoctor().then(response => {
        if (response.data.code == 0) {
          // todo: 和后端记得校对
          this.doctor = response.data.data.doctors;
          this.doctor.forEach(item => {
            this.doctorDict[item.id] = item.doctorName;
          });
          console.log("doctor Dict ", this.doctorDict);
          this.loadPageData();
          console.log("getAlldoctor: ", this.doctor);
        } else {
          console.log("getAlldoctor ERROR!!!");
        }
      });
    },
    save() {
      this.addDialogVisible = false;
      /* 转换格式 */
      if (this.doctorDuty.outpatientDoctorI !== "") {
        this.doctorDuty.outpatientDoctorI = parseInt(
          this.doctorDuty.outpatientDoctorI
        );
      }

      let InsertParam = {
        dayOfWeek: this.doctorDuty.dayOfWeek,
        id: parseInt(this.doctorDuty.id),
        noon: this.doctorDuty.noon,
        outpatientDoctorId: this.doctorDuty.outpatientDoctorI
      };
      if (this.updateFlag) {
        /* update */
        console.log("send update:", InsertParam);
        update(InsertParam).then(response => {
          if (response.data.code == 0) {
            deleteElem({ ids: [InsertParam.id] }).then(re2 => {
              if (re2.data.code == 0) {
                this.loadPageData();
              }
            });
            this.loadPageData();
          }
        });
      } else {
        /* insert */
        console.log("send insert:", InsertParam);
        insert(InsertParam).then(response => {
          if (response.data.code == 0) {
            this.$message("添加成功");
            this.loadPageData();
          } else {
            this.$message("添加失败");
          }
        });
      }
    },
    handleEdit(index, row) {
      this.dialogTitle = "修改";
      this.addDialogVisible = true;
      // 切记此处不可直接赋值,直接赋值的话传递的是引用,先修改再新建的话,就会影响到之前被修改的行
      this.doctorDuty = JSON.parse(JSON.stringify(row));
      this.updateFlag = true;
    },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除此项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          /*todo: 在这里填写在数据库中删除的语句 */
          let deleteParam = { ids: [row.id] };
          console.log("send deleteElem:", deleteParam);
          deleteElem(deleteParam).then(response => {
            if (response.data.code == 0) {
              this.$message("删除成功");
              this.loadPageData();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      // 更新页数
      this.loadPageData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPageNum = val;
      // 更新页数
      this.loadPageData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    },
    batchRemoveButtonClicked() {
      this.$confirm("此操作将永久删除选中项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          /* 先封装成数组,再删除 */
          let removeIds = [];
          this.multipleSelection.forEach(item => {
            removeIds.push(item.id);
          });
          let deleteParam = {
            ids: removeIds
          };
          console.log("send deleteElem:", deleteParam);
          deleteElem(deleteParam).then(response => {
            if (response.data.code == 0) {
              this.$message("删除成功");
              this.loadPageData();
            } else {
              var failedids = "[";
              response.data.data.ids.forEach(item => {
                failedids += item + ",";
              });
              failedids += "]";
              response.data.data.ids;
              this.$message.error("删除 " + failedids + " 失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    queryButtonClicked() {
      this.queryDialogVisible = true;
    },
    queryConfirm() {
      this.queryDialogVisible = false;
      this.currentPageNum = 1;
      this.loadPageData();
    },
    queryResetButtonClicked() {
      /* 补全信息 */
      this.doctorDutyQuery.id = "";
      this.doctorDutyQuery.noon = "";
      this.doctorDutyQuery.dayOfWeek = "";
      this.doctorDutyQuery.outpatientDoctorId = "";
      this.doctorDutyQuery.doctorName = "";
      this.loadPageData();
    }
  }
};
</script>

<style>
</style>